package org.easylookandfeel.adapter;

import javax.swing.AbstractListModel;
import javax.swing.JList;
import javax.swing.UIManager.LookAndFeelInfo;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;

/**
 * A built-in implementation of {@link LookAndFeelAdapter} interface. It builds
 * a look and feel selection on a given {@link JList}. The client application
 * must only pass a reference to {@link JList} where look and feel options will
 * be placed in.
 * 
 * @author pcmnac@gmail.com
 * 
 */
public class ListLookAndFeelAdapter extends AbstractLookAndFeelAdapter {

  /**
   * {@link JList} where look and feel options will be placed in.
   */
  private JList lstLookAndFeels;

  /**
   * Constructor.
   * 
   * @param list
   *          The {@link JList} where look and feel options will be placed.
   */
  public ListLookAndFeelAdapter(JList list) {
    this.lstLookAndFeels = list;
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#handleLookAndFeelChanged(int)
   */
  public void handleLookAndFeelChanged(int lookAndFeelIndex) {
    lstLookAndFeels.setSelectedIndex(lookAndFeelIndex);
  }

  /**
   * @see org.easylookandfeel.adapter.LookAndFeelAdapter#initializeLookAndFeel(javax.swing.UIManager.LookAndFeelInfo[])
   */
  @SuppressWarnings("serial")
  public void initializeLookAndFeel(final LookAndFeelInfo[] looks) {

    if (looks.length > 0) {

      lstLookAndFeels.setModel(new AbstractListModel() {

        /**
         * @see javax.swing.ListModel#getElementAt(int)
         */
        public Object getElementAt(int index) {
          return looks[index].getName();
        }

        /**
         * @see javax.swing.ListModel#getSize()
         */
        public int getSize() {
          return looks.length;
        }
      });

      lstLookAndFeels.addListSelectionListener(new ListSelectionListener() {
        
        /**
         * @see javax.swing.event.ListSelectionListener#valueChanged(javax.swing.event.ListSelectionEvent)
         */
        public void valueChanged(ListSelectionEvent e) {
          getManager().changeLookAndFeel(lstLookAndFeels.getSelectedIndex());
        }
      });
    }

  }
}
